package com.taptech.doufu.ui.fragment;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.taptech.doufu.util.CacheUtil;
import com.taptech.doufu.util.TextUtil;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.adapter.DfCartoonHomeItemAdapter;
import com.taptech.doufu.bean.CartoonHomeBean;
import com.taptech.doufu.util.CommonUtils;
import com.taptech.doufu.listener.CommmonImp;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.FirstItemable;
import com.taptech.doufu.listener.ToUpOrDownable;
import com.taptech.doufu.bean.CartoonDayBean;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.util.TimeUtils234;
import com.taptech.doufu.ui.view.PullToRefreshListView;

import org.json.JSONObject;

import java.io.File;
import java.util.List;

/**
 * 漫画页面日更
 */
public class CartoonDayFragment extends DiaobaoBaseFragment implements PullToRefreshListView.OnLoadAndRefreshListener {
    private PullToRefreshListView listView;
    private List<CartoonHomeBean> contentList;
    private String lastPage = "";//加载请求时所带的特殊字断（等同于pageNo）
    private DfCartoonHomeItemAdapter ada;
    private ImageView ivTop;
    private TextView tvTime;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_dfcartoon, null);
        lastPage = "";
        getDefaultDisplay();
        initsView(rootView);
        onRefresh();
        return rootView;
    }

    private void loadCacheDate() {
        //加载列表
        try {
            if ((lastPage == null) || (lastPage.length() < 1)) {
                JSONObject data3 = CacheUtil.readJsonDataFromCache(new File(CommmonImp.Home_Cartoon_List));
                contentList = com.alibaba.fastjson.JSONArray.parseArray(data3.getJSONArray("list").toString(), CartoonHomeBean.class);
                ada.setNewData(contentList);
                lastPage = data3.getString("last");
                if ((lastPage != null) && (lastPage.length() > 0)) {
                    listView.setLoadmoreable(true);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initsView(View rootView) {
        ivTop = (ImageView) rootView.findViewById(R.id.fragment_dfcartoon_upTop);
        tvTime = (TextView) rootView.findViewById(R.id.tv_dfcartoon_time);
        listView = (PullToRefreshListView) rootView.findViewById(R.id.fragment_dfcartoon_list);
        listView.setRefreshable(true);
        listView.setOnLoadAndRefreshListener(this);
        listView.setFirstItemChangListener(new FirstItemable() {
            @Override
            public void getFirstPos(int pos) {
                if ((pos > 1) && (pos < contentList.size())) {
                    if (contentList != null && contentList.size() > pos - 2) {
                        if (contentList.get(pos - 2).getChapters() != null && contentList.get(pos - 2).getChapters().size() > 0) {
                            tvTime.setText(TimeUtils234.getChineseRuleTime(contentList.get(pos - 2).getChapters().get(0).getCreated_at()));
                            tvTime.setVisibility(View.VISIBLE);
                        }
                    }
                } else {
                    tvTime.setVisibility(View.INVISIBLE);
                }
            }
        });
        listView.setMoveListener(new ToUpOrDownable() {
            @Override
            public void moveToUp() {
                setToTopVisible(false);
            }

            @Override
            public void moveToDown(int firstVisiblePos) {
                if (firstVisiblePos > 2) {
                    ivTop.setVisibility(View.VISIBLE);
                    setToTopVisible(true);
                }
            }
        });
        ivTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listView != null) {
                    listView.setSelection(0);
                }
            }
        });
        initsListViewHeadView();
        loadCacheDate();
    }

    private boolean toTopButtonIsShow = false;

    private void setToTopVisible(boolean visibleAnimation) {
        ObjectAnimator objectAnimators = null;
        AnimatorSet animatorSet = new AnimatorSet();
        if (visibleAnimation) {
            //出现动画
            if (!toTopButtonIsShow) {
                objectAnimators = ObjectAnimator.ofFloat(ivTop, "translationY", com.taptech.doufu.util.ScreenUtil.getScreenHeight(this.getActivity()), 0);
            }
            toTopButtonIsShow = true;
        } else {
            //隐藏动画
            if (toTopButtonIsShow) {
                objectAnimators = ObjectAnimator.ofFloat(ivTop, "translationY", 0, com.taptech.doufu.util.ScreenUtil.getScreenHeight(this.getActivity()) - ivTop.getMeasuredHeight());
            }
            toTopButtonIsShow = false;
        }
        if (objectAnimators != null) {
            animatorSet.setDuration(500);
            animatorSet.playTogether(objectAnimators);
            animatorSet.start();
        }

    }




    /**
     * 装在headView,包括轮播图，下面的标签栏
     */
    private void initsListViewHeadView() {
        ada = new DfCartoonHomeItemAdapter(getActivity(), null);
        listView.setAdapter(ada);
    }

    @Override
    public void onRefresh() {
        //重新加载数据
        lastPage = "";
        if (listView.getLoadCompleteImg() != null) {
            listView.getLoadCompleteImg().setVisibility(View.GONE);
        }
        listView.setFull(false);
        listView.setLoadmoreable(true);
        getDataFromNet();
    }

    private String lastRequest123 = "－999999999.524521";

    @Override
    public void loadMore() {
        if (!CommonUtils.isNetWorkConnected(getActivity())) {
            listView.loadMoreComplete();
            listView.setLoadmoreable(true);
            return;
        }
        if (!lastRequest123.equals(lastPage)) {
            getDataFromNet();
            lastRequest123 = lastPage;
        }
    }

    private void getDataFromNet(){
        ApiClient.getInstance().getService().cartoonTips(lastPage,Constant.PAGE_SIZE_20,0)
                .compose(RxJavaHelper.<CartoonDayBean>observeOnMainThread(getActivity()))
                .subscribe(new BaseSubscriber<CartoonDayBean>(){
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (listView != null) {
                            listView.onRefreshComplete();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        if (listView != null) {
                            listView.onRefreshComplete();
                        }
                    }

                    @Override
                    public void onNext(final CartoonDayBean response) {
                        super.onNext(response);
                        if (response ==null)
                            return;
                        CartoonDayBean.DataBean data = response.getData();
                        if (data == null)
                            return;
                        List<CartoonHomeBean> list = com.alibaba.fastjson.JSONArray.parseArray(new Gson().toJson(data.getList()), CartoonHomeBean.class);
                        String last =data.getLast();
                        try {
                            if (list !=null&& list.size() > 0) {
                                if ((lastPage == null) || (lastPage.length() < 1)) {
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            CacheUtil.saveJsonDataToCache(response.getData().toString(), new File(CommmonImp.Home_Cartoon_List));
                                        }
                                    }).start();
                                    contentList = list;
                                    ada.setNewData(contentList);
                                    if (!TextUtil.isEmpty(last)) {
                                        lastPage = last;
                                    }
                                    listView.loadMoreComplete();
                                    listView.setLoadmoreable(true);
                                } else {
                                    contentList.addAll(list);
                                    ada.notifyDataSetChanged();
                                    if (lastPage.equals(last)) {
                                        listView.getLoadCompleteImg().setImageResource(R.drawable.draw_recommand_bottom_img);
                                        listView.setFull(true);
                                        listView.loadMoreComplete();
                                        listView.setLoadmoreable(false);
                                    } else {
                                        if (!TextUtil.isEmpty(last)) {
                                            lastPage = last;
                                        }
                                    }
                                }
                            } else {
                                listView.getLoadCompleteImg().setImageResource(R.drawable.draw_recommand_bottom_img);
                                listView.setFull(true);
                                listView.loadMoreComplete();
                                listView.setLoadmoreable(false);
                                ada.notifyDataSetChanged();
                                return;
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    private void getDefaultDisplay() {
        DisplayMetrics dpMetrics = new DisplayMetrics();
        getActivity().getWindow().getWindowManager().getDefaultDisplay()
                .getMetrics(dpMetrics);
    }
}